from uliweb.orm import *

wiki_formats = [('rst', 'reStructuredText')]

class WikiPage(Model):
    name = Field(CHAR, max_length=100, index=True, unique=True)
    title = Field(unicode, max_length=200)
    content = Field(TEXT)
    format = Field(CHAR, max_length=20, choices=wiki_formats, default='rst')
    creator = Reference('user')
    create_time = Field(datetime.datetime, auto_now_add=True)
    modify_time = Field(datetime.datetime, auto_now_add=True, auto_now=True)
    deleted = Field(bool)
    
    def new_revision(self, old_content='', old_title='', old_format='', editor=None):
        '''Create a new ChangeSet with the old content.'''
    
        cs = WikiChangeSet(
            wiki=self,
            editor=editor,
            old_title=old_title,
            old_format=old_format,
            old_content=old_content).save()
        
        return cs
    
class WikiChangeSet(Model):
    wiki = Reference(WikiPage, collection_name='changeset')
    editor = Reference('user')
    revision = Field(int)
    old_title = Field(unicode, max_length=200)
    old_format = Field(CHAR, max_length=20, choices=wiki_formats)
    old_content = Field(TEXT)
    modify_time = Field(datetime.datetime, auto_now_add=True)
    reverted = Field(bool)
    
    def save(self):
        if self.id is None:
            lastest = WikiChangeSet.filter(WikiChangeSet.c.wiki==self.wiki.id)\
                .order_by(WikiChangeSet.c.id.desc()).one()
#            lastest = list(WikiChangeSet.filter(WikiChangeSet.c.wiki==self.wiki.id)\
#                .order_by(WikiChangeSet.c.id.desc()))[0]
            if lastest:
                self.revision = lastest.revision + 1
            else:
                self.revision = 1
        super(WikiChangeSet, self).save()
    